import {IParams} from './params'
import * as step from '@flow-step/step-toolkit'
import {checkCustomRuleDir} from './utils'
import * as fs from 'fs'
import path from 'path'

export function getRule(params: IParams): string{
    let rule : string
    step.info(`useCustomRule=${params.useCustomRule}`)

    if(params.useCustomRule) {
        step.info(`USE CUSTOM RULE FILES`)
        const customRuleDir = checkCustomRuleDir(params.customRuleDir)
        // search for xml files in custom rule dir
        const foundRules = fs.readdirSync(customRuleDir)
            .filter(file => file.endsWith('.xml'))
            .map(file => path.join(customRuleDir, file));
        if (foundRules.length === 0) {
            throw new Error(`No xml suffixed file found in custom rule dir ${customRuleDir}.`)
        }
        rule = foundRules.join(',');
        step.info(`found custom rule files: ${rule}`)

    }else{
        step.info(`ruleSet=${params.ruleSet}`)
        if (!params.ruleSet) {
            throw new Error(`ruleSet is not set.`)
        }
        const rules: string[] = params.ruleSet.split(',').map(file => `${params.pluginDir}/p3c/rule/java/${file}`);
        rule = rules.join(',');
    }

    return rule
}